package com.shaper2.minaapps;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.*;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.maps.*;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class Main extends MapActivity {
    private MapView mapView;
    private List<Overlay> mapOverlays;
    private LocationManager locationManager;
    private MyLocationListener locationListener;
    private MySQLiteDatabaseHandler databaseHandler;
    private MyMapUpdater mapUpdater;
    private boolean tracked;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        databaseHandler = new MySQLiteDatabaseHandler(this);
        SQLiteDatabase database = databaseHandler.getWritableDatabase();
        databaseHandler.onUpgrade(database, 0, 0);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener(this, databaseHandler);
        mapUpdater = new MyMapUpdater(mapOverlays, mapView, databaseHandler);
        locationListener.addObserver(mapUpdater);
        tracked = false;
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(tracked){
            locationManager.removeUpdates(locationListener);
            tracked = false;
            Toast.makeText(this, "GPS tracking is off", Toast.LENGTH_SHORT).show();
        }
        else{
            locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 5000, 10, locationListener);
            tracked = true;
            Toast.makeText(this, "GPS tracking is on", Toast.LENGTH_SHORT).show();
        }
        return true;
    }
}
